package com.guigu.qingcheng.controller;


import com.aliyun.oss.OSS;
import com.guigu.qingcheng.config.OssConfig;
import com.guigu.qingcheng.service.OssService;
import com.guigu.qingcheng.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/oss")
public class OssController {
    @Autowired
    private OssService ossService;

    @Value("${aliyun.oss.file.bucketname}")
    private String buckname;

    @PostMapping()
    public R upladeFile(MultipartFile file){
        String fileUrl = ossService.uplateFile(file);
        return R.ok().data("fileUrl",fileUrl);
    }

    @RequestMapping("/ossDelete")
    public void ossDelete(String fileName){
        String[] split = fileName.split("/");
        StringBuffer s= new StringBuffer();
        for (int i = 3; i < split.length; i++) {
            s.append(split[i]);
            s.append("/");
        }
        String str=s.toString();
        this.getOssClient().deleteObject(buckname,str.substring(0,str.length()-1));

        // 批量删除文件。key等同于ObjectName，表示删除OSS文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
//    List<String> keys = new ArrayList<String>();
//    keys.add("key0");
//    keys.add("key1");
//    keys.add("key2");
//    DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(BUCKETNAME).withKeys(keys));
//    List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();

        this.getOssClient().shutdown();
    }

    private OSS getOssClient(){
        return OssConfig.ossClient();
    }
}
